package com.city.parking.util;

import java.net.URLDecoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.city.parking.ParkingApp;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

public class HttpClientUtil {
	private static Handler mHandler = null;	
	private static HttpClientUtil mSelf = new HttpClientUtil();
	static String TAG = "ParkingHttp";
	
	public HttpClientUtil() {
        HandlerThread thread = new HandlerThread("http");
        thread.start();
        mHandler = new Handler(thread.getLooper());
	}
	
    public static boolean get(final HttpRequest req) {
    	if (!req.isValide())
    		return false;

        Runnable getRunnable = new Runnable() {
            @Override
            public void run() {
            	Message net_msg = doGet(req);
            	if (req.callback != null)
            		req.callback.sendMessage(net_msg);
            }
        };
        mHandler.post(getRunnable);
        return true;
    }
    
	private static Message doGet(HttpRequest req) {
		// TODO Auto-generated method stub
		Message message = new Message();
		message.what = req.id;
		message.arg1 = HttpRequest.NET_ERROR;
		message.obj = null;
		Log.i(TAG, "get from " + req.url);

		String returnContent = "";
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(req.url);
		httpget.addHeader("token", ParkingApp.APPTOKEN);

		try {
			HttpResponse response = httpclient.execute(httpget);
			int status = response.getStatusLine().getStatusCode();
			Log.i(TAG, "status = " + status);
			String returnXML = EntityUtils.toString(response.getEntity());
			returnContent = URLDecoder.decode(returnXML);
			if (returnContent != null && !returnContent.equals(""))
				Utils.log(returnContent);
			switch (status) {
			case 200:
				message.arg1 = HttpRequest.NET_SUCCESS;
				message.obj = HttpResult.fromJson(returnContent);
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return message;
	}

    public static boolean post(final HttpRequest req) {
    	if (!req.isValide())
    		return false;

        Runnable postRunnable = new Runnable() {
            @Override
            public void run() {
            	Message net_msg = doPost(req);
            	if (req.callback != null)
            		req.callback.sendMessage(net_msg);
            }
        };
        mHandler.post(postRunnable);
        return true;
    }
    
	private static Message doPost(HttpRequest req) {
		// TODO Auto-generated method stub
		Message message = new Message();
		message.what = req.id;
		message.arg1 = HttpRequest.NET_ERROR;
		message.obj = null;
		Log.i(TAG, "post " + req.postData + " to " + req.url);

		String returnContent = "";
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(req.url);
		httppost.addHeader("token", ParkingApp.APPTOKEN);

		try {
			StringEntity se = new StringEntity(req.postData, "UTF-8");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
		    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
			httppost.setEntity(se);
			HttpResponse response = httpclient.execute(httppost);
			int status = response.getStatusLine().getStatusCode();
			Log.i(TAG, "status = " + status);
			String returnXML = EntityUtils.toString(response.getEntity());
			returnContent = URLDecoder.decode(returnXML);
			if (returnContent != null && !returnContent.equals(""))
				Utils.log(returnContent);
			switch (status) {
			case 200:
				message.arg1 = HttpRequest.NET_SUCCESS;
				message.obj = HttpResult.fromJson(returnContent);
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return message;
	}
}
